﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using EntLibEC.Cmn;

namespace EntLibEC.Biz.Security
{
    public class SqlInjectionScreeningModule : IHttpModule
    {        
        //Defines the set of characters that will be checked.
        //You can add to this list, or remove items from this list, as appropriate for your site
        public static string[] blackList = {";--","/*","*/","@@",
                                           "char","nchar","varchar","nvarchar",
                                           "sysobjects","syscolumns"};

        public void Dispose()
        {
            //no-op 
        }

        //Tells ASP.NET that there is code to run during BeginRequest
        public void Init(HttpApplication app)
        {
            app.BeginRequest += new EventHandler(app_BeginRequest);
        }

        //For each incoming request, check the query-string, form and cookie values for suspicious values.
        void app_BeginRequest(object sender, EventArgs e)
        {
            HttpRequest Request = (sender as HttpApplication).Context.Request;

            string path = Request.Path;

            foreach (string key in Request.QueryString)
                CheckInput(Request.QueryString[key], key, path);
            foreach (string key in Request.Form)
                CheckInput(Request.Form[key], key, path);
            foreach (string key in Request.Cookies)
                CheckInput(Request.Cookies[key].Value, key, path);
        }

        //The utility method that performs the blacklist comparisons
        //You can change the error handling, and error redirect location to whatever makes sense for your site.
        private void CheckInput(string parameter, string key, string path)
        {
            for (int i = 0; i < blackList.Length; i++)
            {
                if ((parameter.IndexOf(blackList[i], StringComparison.OrdinalIgnoreCase) >= 0))
                {
                    //
                    //Handle the discovery of suspicious Sql characters here
                    //
                    ErrorLog.GetInstance().Write("SqlInjectionScreeningModule --  Key: " + key + Environment.NewLine +
                        "BlackList: " + blackList[i] + Environment.NewLine +
                        " Parameter: " + parameter + Environment.NewLine + 
                        " Path: " + path);
                    HttpContext.Current.Response.Redirect("~/mgmt/ShowError.aspx");  //generic error page on your site
                }
            }
        }

    }
}